<template>
    <div>
        <div class="container">
            <el-button type="warning" :icon="CirclePlusFilled" style="margin-bottom: 10px" @click="visible = true">新增</el-button>
           <el-table
          :data="tableData"
          :preserve-expanded-content="true"
          style="height: calc(100vh - 300px);"
        >
            <el-table-column label="序号" prop="labelId" width="80" />
            <el-table-column label="贷款公司" prop="companyName" />
            <el-table-column label="银行" prop="bankName" />
            <el-table-column label="二级网点" prop="level2Bank" />
            <el-table-column label="授信额度(元)" prop="loanAmount" />
            <el-table-column label="提用额度(元)" prop="usedAmount" />
            <el-table-column label="未提用额度(元)" prop="unusedAmount" />
            <el-table-column label="年利率(%)" prop="rate" />
            <el-table-column label="贷款到期日期" prop="dueDate" />
            <el-table-column label="最近录入时间" prop="updateTime" />
          <el-table-column label="操作" width="450px">
                <template #default="{ row: flowRow }">
                    <el-button type="primary" size="small" :icon="View" @click="handleView(flowRow)">
                        查看
                    </el-button>
                    <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(flowRow)">
                        编辑
                    </el-button>
                    <el-button type="primary" size="small" :icon="Edit" @click="handleEditRate(flowRow)">
                        调整利率
                    </el-button>
                    <el-button type="primary" size="small" :icon="Edit" @click="handleEditUsed(flowRow)">
                        额度提用
                    </el-button>
                    <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(flowRow)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
          <el-pagination v-if="hasPagination" :page-size="page.size" :background="false"
                         :page-sizes="[10, 20, 50, 100]"  @size-change="handleSizeChange"
                         layout="sizes,prev, pager, next" :total="page.total" @current-change="handleCurrentChange" style="margin-top: 10px" />
        </div>
        <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="800px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" />
        </el-dialog>

        <!-- 调整利率弹窗 -->
        <el-dialog :title="'调整利率'" v-model="visibleRate" width="500px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialogRate">
            <TableEdit :form-data="rowData" :options="optsRate" :edit="isEdit" :update="updateData" />
        </el-dialog>

        <!-- 额度提用弹窗 -->
        <el-dialog :title="'额度提用'" v-model="visibleUsed" width="500px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialogUsed">
            <TableEdit :form-data="rowData" :options="optsUsed" :edit="isEdit" :update="updateData" />
            
        </el-dialog>

        <el-dialog title="查看详情" v-model="visible1" width="800px" destroy-on-close>
            <TableDetail :data="viewData"></TableDetail>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="loan-management">
import { ref, reactive,onMounted } from 'vue';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { Delete, Edit, View, Refresh } from '@element-plus/icons-vue';
import { fetchLoanData,saveLoanData,delLoanDataById,fetchCompanyData,fetchBankLeve2 } from '@/api';
import { Loan } from '@/types/dto';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import { handleExcelImport } from '@/utils';
import { ElMessageBox } from 'element-plus';


const hasPagination = ref(true);
const visibleRate = ref(false);
const visibleUsed = ref(false);


onMounted(async () => {
    const res = await fetchCompanyData();
    const opts = res.data.map(item => ({
        label: item.companyName,
        value: item.companyName
    }));
    const companyItem = options.value.list.find(item => item.prop === 'companyName');
    if (companyItem) {
        companyItem.opts = opts;
    }
});

// 处理Excel上传
const handleExcelUpload = async (options: any) => {
    await handleExcelImport(options, async (data) => {
        // 这里处理解析后的Excel数据
        console.log('解析后的Excel数据:', data);
        // 可以在这里调用API将数据保存到服务器
        ElMessage.success(`成功导入 ${data.length} 条数据`);
        // 重新加载表格数据
        getData();
    });
};

const handleCurrentChange = (val: number) => {
    page.index = val;
    page.currentPage = val;
    getData();
};

const changePage = (val: number) => {
	page.index = val;
    page.currentPage = val;
	getData();
};

const handleSizeChange = (val: number) => {
    page.size = val;
    page.index = 1;
    page.currentPage = 1;
    getData();
};

const page = reactive({
    total: 0,
    index: 1,
    size: 50,
    hasPagination: true,
    layout: 'prev, pager, next,total',
    currentPage: 1,
    pageCount: 1
})
const tableData = ref<Loan[]>();
const getData = async () => {
    const res = await fetchLoanData(page.index, page.size);
    tableData.value = res.data.content;
    tableData.value.forEach((item, index) => {
        item.labelId = index + 1 + (page.index - 1) * page.size;
        item.unusedAmount = item.loanAmount - item.usedAmount;
    })
    page.index = res.data.number + 1;
    page.total = res.data.totalElements;
    page.size = res.data.size;
    page.pageCount = res.data.totalPages;

    const res1 = await fetchBankLeve2(1,100);
    const cascaderOptions = res1.data.content.reduce((acc, curr) => {
  // 查找是否已存在一级节点
  const existLevel = acc.find(item => item.value === curr.level1);
    
    if (!existLevel) {
        acc.push({
        value: curr.level1,
        label: curr.level1,
        children: [{
            value: curr.level2,
            label: curr.level2,
            rawData: curr // 保留原始数据
        }]
        });
    } else {
        existLevel.children.push({
        value: curr.level2,
        label: curr.level2,
        rawData: curr
        });
    }
    return acc;
    }, []);
    options.value.list[2].opts = cascaderOptions;

};

const saveLoan = async (data: Loan) => {
    // 这里可以添加调用API的逻辑来新增贷款
    data.bankName = data.bank[0];
    data.level2Bank = data.bank[1]; 
    await saveLoanData(data); 
    getData();
};

const delLoanData = async (id) => {
    // 这里可以添加调用API的逻辑来新增公司
    await delLoanDataById(id); 
    getData();
};
getData();


// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '120px',
    span: 12,
    list: [
        { type: 'input', label: '序号', prop: 'id', required: false, disabled: true},
        { type: 'select', prop: 'companyName', label: '贷款公司' , required: true },
        { type: 'cascader', prop: 'bank', label: '贷款银行' , required: true },
        { type: 'number', prop: 'loanAmount', label: '授信额度(元)' , required: true },
        { type: 'number', prop: 'usedAmount', label: '提用额度(元)' , required: true },
        { type: 'number', prop: 'rate', label: '年利率(%)' , required: true },
        { type: 'date',format: 'YYYY-MM-DD', prop: 'dueDate', label: '到期日期' , required: true }
    ]
})

const optsRate = ref<FormOption>({
    labelWidth: '120px',
    span: 12,
    list: [
        {
            prop: 'rate',
            label: '年利率(%)',
            type: 'number',
            placeholder: '请输入年利率',
            required: true
        }
    ]
});

const optsUsed = ref<FormOption>({
    labelWidth: '120px',
    span: 12,
    list: [
        {
            prop: 'usedAmount',
            label: '提用额度(元)',
            type: 'number',
            placeholder: '请输入提用额度',
            required: true
        }
    ]
});

const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const handleEdit = (row: Loan) => {

    rowData.value = { ...row };
    rowData.value.bank = [rowData.value.bankName, rowData.value.level2Bank];
    isEdit.value = true;
    visible.value = true;
};

const handleEditUsed = (row: Loan) => {
    rowData.value = { ...row };
    rowData.value.bank = [rowData.value.bankName, rowData.value.level2Bank];
    isEdit.value = true;
    visibleUsed.value = true;
};

const handleEditRate = (row: Loan) => {
    rowData.value = { ...row };
    rowData.value.bank = [rowData.value.bankName, rowData.value.level2Bank];
    isEdit.value = true;
    visibleRate.value = true;
};

const updateData = async (data: Loan) => {
    console.log(data);
    console.log(data.usedAmount)
    if (data.usedAmount > data.loanAmount) {
        ElMessage.error('提用额度不能大于授信额度');
        return;
    }
    await saveLoan(data);
    if (!isEdit.value) {
        ElMessage.success('新增成功');
    } else {
        ElMessage.success('编辑成功');
    }
    closeDialog();
    closeDialogRate();
    closeDialogUsed();
    getData();
};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
};

const closeDialogUsed = () => {
    visibleUsed.value = false;
    isEdit.value = false;
}

const closeDialogRate = () => {
    visibleRate.value = false;
    isEdit.value = false;
}

// 查看详情
const visible1 = ref(false);
const viewData = ref({
    row: {},
    list: []
});
const handleView = (row: Loan) => {
    console.log(row);
    row.bank = [row.bankName, row.level2Bank];
    viewData.value.row = { ...row };
    visible1.value = true;
    viewData.value.list = [{type:"id", prop : 'id', label: '序号'},
    { prop: 'companyName', label: '贷款公司' },
    { prop: 'bankName', label: '银行' },
    { prop: 'level2Bank', label: '二级网点' },
    { prop: 'loanAmount', label: '授信额度(元)' },
    { prop: 'usedAmount', label: '提用额度(元)' },
    { prop: 'unusedAmount', label: '未提用额度(元)' },
    { prop: 'rate', label: '年利率(%)' },
    { prop: 'dueDate', label: '贷款到期日期' }]
};
const handleDelete = async (row: Loan) => {

    ElMessageBox.confirm('确定要删除吗？', '提示', {
        type: 'warning'
    })
        .then(async () => {
            await delLoanData(row.id);
            await getData();
            ElMessage.success('删除成功');
        })
        .catch(() => { });
};
</script>

<style>

.container {
    min-height: calc(100vh - 150px) !important; 
    box-sizing: border-box;
    background: #fff;
    padding: 20px;
    overflow: auto;
}

.el-table.no-header-bg th {
    height: 40px;
    background-color: #fff !important;
    font-weight: normal;
    text-align: center !important;

}
.el-table th.el-table__cell  {
    text-align: center !important;
}

.el-table td.el-table__cell{
    text-align: center !important;
}
</style>